import db from '@/mock/createDB'
import Mock from 'mockjs'
import md5 from 'js-md5'
import jwt from 'jsonwebtoken'

// 登录
Mock.mock('/user/login', 'post', function (info) {
  const { userName, password } = JSON.parse(info.body)
  const stateResult = db.select('users_table', (item:any) => item.userName === userName && item.status === 2)
  const result = db.select('users_table', (item:any) => item.userName === userName && item.password === password && item.status === 1)
  if (stateResult && stateResult.length > 0) {
    return { code: 1001, message: '你的账号还未激活' }
  }
  if (result && result.length > 0) {
    let token = ''
    try {
      // 登录成功颁发授权码  token expiresIn 过去时间 1h表示1小时后，30表示30秒
      token = jwt.sign({ data: userName }, 'zhiyuanzuishuai', { expiresIn: '1d' })
    } catch (err) {
      console.log(err)
    }
    return { code: 0, message: '登录成功', token, data: result}
  } else {
    return { code: 1002, message: '账号或密码错误' }
  }
})